#首次适应算法
class MemoryBlock:
    def __init__(self, start, size, free=True):
        self.start = start
        self.size = size
        self.free = free
        self.next = None

def first_fit_allocate(block, size):
    current = block
    while current:
        if current.free and current.size >= size:
            if current.size > size:
                # 分割空闲块
                new_block = MemoryBlock(current.start + size, current.size - size, True)
                new_block.next = current.next
                current.next = new_block
            current.size = size
            current.free = False
            return True
        current = current.next
    return False

# 示例运行
root = MemoryBlock(0, 1024)
print("首次适应分配结果（分配 200）：", first_fit_allocate(root, 200))


#最佳适应算法
def best_fit_allocate(block, size):
    best = None
    current = block
    while current:
        if current.free and current.size >= size:
            if not best or current.size < best.size:
                best = current
        current = current.next
    if best:
        if best.size > size:
            new_block = MemoryBlock(best.start + size, best.size - size, True)
            new_block.next = best.next
            best.next = new_block
        best.size = size
        best.free = False
        return True
    return False

# 示例运行
root = MemoryBlock(0, 1024)
print("最佳适应分配结果（分配 200）：", best_fit_allocate(root, 200))


#最坏适应算法
def worst_fit_allocate(block, size):
    worst = None
    current = block
    while current:
        if current.free and current.size >= size:
            if not worst or current.size > worst.size:
                worst = current
        current = current.next
    if worst:
        if worst.size > size:
            new_block = MemoryBlock(worst.start + size, worst.size - size, True)
            new_block.next = worst.next
            worst.next = new_block
        worst.size = size
        worst.free = False
        return True
    return False

# 示例运行
root = MemoryBlock(0, 1024)
print("最坏适应分配结果（分配 200）：", worst_fit_allocate(root, 200))